package autoWeb;

import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import java.util.*;


public class AutoWebTest {

    public static void main(String[] args) throws IOException, InterruptedException {

        // 1. 配置浏览器驱动
        System.setProperty("webdriver.chrome.driver", "D:\\software\\chrome-win64\\chromedriver-win64\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        try {
            // 2. 打开目标网页
            driver.get("https://scjgj.jszwfw.gov.cn/apply/#/apply/handle?jrsO423dzsUP%2FJ9o%2Fre1hzbUZffE2BRbmNYKvTRHecM%3D");

            // 3. 登录流程 -----------------------------------------------------------
            // 定位并填写用户名密码
            new WebDriverWait(driver, 120)
                    .until(ExpectedConditions.presenceOfElementLocated(
                            By.cssSelector("input.ant-input.ant-input-lg[placeholder='请输入用户名']")))
                    .sendKeys("15061893400");

            driver.findElement(By.cssSelector("input.ant-input.ant-input-lg[placeholder='请输入密码'][type='password']"))
                    .sendKeys("12Baoyicheng,,");
            // 智能等待验证码手动输入（两种方案）
            System.out.println("⏳ 请手动输入验证码后执行登录操作...");

            // 4. 定位ANT DESIGN登录按钮
            WebElement loginButton = new WebDriverWait(driver, 10)
                    .until(ExpectedConditions.elementToBeClickable(
                            By.cssSelector("button.ant-btn-primary[type='submit']")));

            System.out.println("⏳ 请手动输入验证码后点击登录按钮...");

            // 5. 智能等待登录完成（两种方案可选）
            // 方案A：等待登录按钮不可见（推荐）
            new WebDriverWait(driver, 120).until(ExpectedConditions.invisibilityOf(loginButton));

            System.out.println("✅ 登录成功！等待2秒确保页面稳定...");
            Thread.sleep(2000); // 登录后额外等待

            // 4. 数据处理流程 ------------------------------------------------------
            String inputFilePathA = "D:\\BaiduSyncdisk\\工作\\梁溪工作\\梁溪战客补传证件集团.xlsx";
            try (FileInputStream fis = new FileInputStream(inputFilePathA);
                 Workbook workbook = new XSSFWorkbook(fis)) {
                //单元格格式
                DataFormatter formatter = new DataFormatter();

                Sheet sheet = workbook.getSheetAt(0);
                for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {

                    Row row = sheet.getRow(rowIndex);
                    if (row == null) continue;
                    // 提取数据
                    String name = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).toString();
                    Cell jituanCell = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                    String jituan = formatter.formatCellValue(jituanCell);

                    String zhizhao = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).toString();
                    Cell shiCell = row.getCell(10, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                    String shi = row.getCell(10, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).toString();
                    if (zhizhao.length() != 18){
                        shiCell.setCellValue("否");
                        continue;
                    }
                    if (StringUtil.isNotBlank(shi)){
                        continue;
                    }

                    //清空
                    String os = System.getProperty("os.name").toLowerCase();
                    String modifierKey = String.valueOf(os.contains("mac") ? Keys.COMMAND : Keys.CONTROL);
                    // 填写经营者名称（先清空再输入）
                    WebElement nameInput = new WebDriverWait(driver, 10)
                            .until(ExpectedConditions.elementToBeClickable(
                                    By.cssSelector("input.ant-input[placeholder='请输入经营者名称']")));
                    // 先点击聚焦
                    nameInput.click();
                    // 全选删除（MAC用COMMAND，Windows用CONTROL）
                    nameInput.sendKeys(modifierKey + "a"); // 全选
                    nameInput.sendKeys(Keys.DELETE);       // 删除
                    Thread.sleep(300);                 // 必须等待
                    nameInput.sendKeys(name);
                    // 填写社会信用代码（先清空再输入）
                    WebElement codeInput = driver.findElement(
                            By.cssSelector("input.ant-input[placeholder='请输入社会信用代码(证件号)']"));
                    // 点击聚焦
                    codeInput.click();
                    // 全选删除（MAC用COMMAND，Windows用CONTROL）
                    codeInput.sendKeys(modifierKey + "a"); // 全选
                    codeInput.sendKeys(Keys.DELETE);       // 删除
                    Thread.sleep(300);
                    codeInput.sendKeys(zhizhao);

                    System.out.printf("✅ 已填写第%d行：%s | %s%n", rowIndex+1, name, zhizhao);

                    // 1. 点击"导入电子营业执照"按钮（修改后的定位方式）
                    WebElement importBtn = new WebDriverWait(driver, 20)
                            .until(ExpectedConditions.elementToBeClickable(
                                    // 根据提供的HTML结构精确定位
                                    By.xpath("//button[contains(@class,'ant-btn-primary')]//span[contains(text(),'导入电子营业执照')]/parent::button")
                            ));
                    importBtn.click();
                    System.out.println("✅ 已点击导入电子营业执照按钮");

                    // 2. 检测图片是否生成（10秒超时）
                    try {
                        WebElement imageLink = new WebDriverWait(driver, 10)
                                .until(ExpectedConditions.presenceOfElementLocated(
                                        By.cssSelector("a.ant-upload-list-item-name[href^='data:image']")
                                ));
                        System.out.println("✅ 检测到电子营业执照图片生成");
                        // 3. 提取并保存图片
                        String base64Data = imageLink.getAttribute("href")
                                .replace("data:image/jpg;base64,", "");
                        byte[] imageBytes = Base64.getDecoder().decode(base64Data);
                        File outputDir = new File("C:\\Users\\Gunjo\\Desktop\\执照保存");
                        if (!outputDir.exists()) outputDir.mkdirs();
                        File outputFile = new File(outputDir, jituan + ".jpg");
                        FileUtils.writeByteArrayToFile(outputFile, imageBytes);
                        System.out.println("💾 图片已保存至: " + outputFile.getAbsolutePath());

                        Thread.sleep(1000);
                        shiCell.setCellValue("是");

                        WebElement imageContainer = driver.findElement(
                                By.cssSelector(".ant-upload-list-item")
                        );
                        ((JavascriptExecutor)driver).executeScript(
                                "arguments[0].remove();",
                                imageContainer
                        );

                    } catch (org.openqa.selenium.TimeoutException e) {  // 捕获 WebDriverWait 的超时异常
                        System.out.println("❌ 图片生成失败（等待10秒超时），跳过当前行");
                        shiCell.setCellValue("否");
                        continue;
                    }

                    if (rowIndex % 10 == 0){
                        System.out.println(rowIndex + "行保存");
                        // 将修改后的workbook写入文件
                        try (FileOutputStream fos = new FileOutputStream(inputFilePathA)) {
                            workbook.write(fos);
                        }
                    }
                }
                // 将修改后的workbook写入文件
                try (FileOutputStream fos = new FileOutputStream(inputFilePathA)) {
                    workbook.write(fos);
                }
            }
        } finally {
            driver.quit(); // 确保浏览器关闭
        }
    }


}
